import { _decorator, Component, Node, view, LabelComponent, CCString} from "cc";
import i18n from './LanguageData';

const { ccclass, property } = _decorator;
@ccclass("LocalizedLabel")
export default class LocalizedLabel extends Component {

    _debouncedUpdateLabel: any = null;
    label: LabelComponent = null;
    
    static editor = {
        executeInEditMode: true,
        menu: 'i18n/LocalizedLabel'
    }

    @property(CCString)
    _dataID: string = "";

    @property
    set dataID (val: string) {
        if (this._dataID !== val) {
            this._dataID = val;

            if (CC_EDITOR) {
                this._debouncedUpdateLabel && this._debouncedUpdateLabel();
            } else {
                this.updateLabel();
            }
        }
    }

    get dataID() {
        return this._dataID;
    }
    
    onLoad () {
        if(CC_EDITOR) {
            this._debouncedUpdateLabel = this.debounce(this.updateLabel, 200);
        }
        if (!i18n.inst) {
            i18n.init();
        }
        cc.log('dataID: ' + this.dataID + ' value: ' + i18n.t(this.dataID));
        this.fetchRender();
    }

    fetchRender () {
        let label = this.getComponent(LabelComponent);
        if (label) {
  
            this.label = label;

            this.updateLabel();
            return;
        } 
    }

    updateLabel () {
        if (!this.label) {
            cc.error('Failed to update localized label, label component is invalid!');
            return;
        }
        let localizedString = i18n.t(this.dataID, {});
        if (localizedString) {
            this.label.string = i18n.t(this.dataID, {});
        }
    }

    debounce(func, wait, immediate ?: number) {
        var timeout;
        return function() {
            var context = this, args = arguments;
            var later = function() {
                timeout = null;
                if (!immediate) func.apply(context, args);
            };
            var callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) func.apply(context, args);
        };
    }
}
